#include <emscripten/html5.h>
#include <emscripten.h>
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <vector>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>

// 问题遗留，浏览器　最多16个gl context, 调用emscripten_webgl_destroy_context 并且　remove canvas element 也没有用，　仍然有　浏览器　警告报出
//  而且很恶劣的是　"Oldest context will be lost"
// 需要继续研究　一下　调用emscripten_webgl_destroy_context 并且　remove canvas element 到底能否起作用


struct Window {
	std::string canvasSelector;
	EMSCRIPTEN_WEBGL_CONTEXT_HANDLE glContext;
};

std::vector<Window> vecContext;

void render() {
	for (auto itor=vecContext.begin(); itor!=vecContext.end(); ++itor){
		emscripten_webgl_make_context_current(itor->glContext);
		auto r = (itor-vecContext.begin()) * 0.05f;
		glClearColor(r, 0.5f, 0.5f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);
	}	
}

Window createCanvas(int idx){
	EM_ASM({
		var id = "c"+$0;
		var c = document.createElement("canvas");
		c.id = id;
		c.style = "width:50px;height:50px;margin:4px;border:1px solid black";
		document.body.appendChild(c);
	}, idx);

	EmscriptenWebGLContextAttributes attribs;
	emscripten_webgl_init_context_attributes(&attribs);
	attribs.alpha = false;
	attribs.enableExtensionsByDefault = false;
	attribs.preserveDrawingBuffer = true;		// 告诉 浏览器 swapbuffers 时 是 "拷贝" 而不是 "交换"
	char selector[16]; sprintf(selector, "#c%d", idx);
	auto context = emscripten_webgl_create_context(selector, &attribs);
	assert(context);

	Window win = { std::string(selector), context };
	return win;
}

void destroyCanvas(Window win){
	auto result = emscripten_webgl_destroy_context(win.glContext);
	assert(result == EMSCRIPTEN_RESULT_SUCCESS);
	EM_ASM({
		var s = UTF8ToString($0);
		var c = document.querySelector(s);
		c.remove();
	}, win.canvasSelector.c_str());
}

int main(){
	emscripten_set_main_loop(render, 0, true);
}

int g_idx = 0;

extern "C"{
	void EMSCRIPTEN_KEEPALIVE createGLContext(){
		auto win = createCanvas(++g_idx);
		vecContext.push_back(win);
	}
	void EMSCRIPTEN_KEEPALIVE destroyGLContext(){
		// printf("des \n");
		if (vecContext.empty()) { return; }
		// printf("des1 \n");
		auto win = vecContext.front();
		destroyCanvas(win);
		// printf("des2 %s \n", win.canvasSelector.c_str());
		vecContext.erase(vecContext.begin());
		// printf("des3 %lu \n", vecContext.size());
	}
}
